package com.clz.workorder.viewmodel

import android.text.TextUtils
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ApiUtils
import com.blankj.utilcode.util.ObjectUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ComplaintDeptBean
import com.czl.base.data.bean.OrderTypeBean
import com.czl.base.data.bean.UserBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriber200Helper
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ComplaintTurnViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model)  {


    val uc = UiChangeEvent()
    val typeName = ObservableField("")
    val deptName = ObservableField("")
    val repairerName = ObservableField("")
    var repairType = ""
    var no = ""
    var memo = ""
    var repairerId = ""
    var subTypeId = ""
    var deptId = ""

    class UiChangeEvent {
        val queryTypeCompleteEvent: SingleLiveEvent<List<OrderTypeBean>> = SingleLiveEvent()
        val queryUserCompleteEvent: SingleLiveEvent<List<UserBean>> = SingleLiveEvent()
        val openTypePopEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val openUserPopEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val turnOrderEvent: SingleLiveEvent<Void> = SingleLiveEvent()



        val queryDeptCompleteEvent:SingleLiveEvent<List<ComplaintDeptBean>> = SingleLiveEvent()
    }

    val onCommentChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        memo = it
    })

    val btnSubmitClick: BindingCommand<Any> = BindingCommand(BindingAction {
        turn()
    })

    val onChoiceDeptClick: BindingCommand<Any> = BindingCommand(BindingAction {
        getDeptByCompanyId(true)
    })
    val onChoiceUserClick: BindingCommand<Any> = BindingCommand(BindingAction {
        getUsersByDeptId()
    })
    private fun turn(){
        if (ObjectUtils.isEmpty(repairerId)) {
            showNormalToast("请选择处理人")
            return
        }
        if (TextUtils.isEmpty(memo)){
            showNormalToast("请描述转单原因")
            return
        }
        if (TextUtils.isEmpty(subTypeId)){
            model.queryWorkOrderType(repairType,model.getAreaId()).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .doOnSubscribe { showLoading() }
                .concatMap { it ->
                    val observable= if (it.code==200){
                        subTypeId= it.data!![0].id
                        model.turnComplaint(
                            mapOf(
                                "memo" to memo,
                                "no" to no,
                                "repairerId" to repairerId,
                                "subTypeId" to subTypeId
                            )
                        )
                    }else{
                        Observable.error(Throwable(it.msg))
                    }
                    observable
                }.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiSubscriber200Helper<BaseBean<Any>>() {
                    override fun onResult(t: BaseBean<Any>) {
                        dismissLoading()
                        uc.turnOrderEvent.call()
                        showSuccessToast(t.msg)
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
//            model.queryWorkOrderType(repairType)
//                .compose(RxThreadHelper.rxSchedulerHelper(this))
//                .doOnSubscribe { showLoading() }
//                .subscribe(object : ApiSubscriber200Helper<BaseBean<List<OrderTypeBean>>>() {
//                    override fun onResult(t: BaseBean<List<OrderTypeBean>>) {
//                        subTypeId= t.data!![0].id
//                        turnComplaint()
//                    }
//
//                    override fun onFailed(msg: String?) {
//                        dismissLoading()
//                        showErrorToast(msg)
//                    }
//
//                })
        }else{
            turnComplaint()
        }
    }

    private fun turnComplaint() {
        model.turnComplaint(
            mapOf(
                "memo" to memo,
                "no" to no,
                "repairerId" to repairerId,
                "subTypeId" to subTypeId
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriber200Helper<BaseBean<Any>>() {
                override fun onResult(t: BaseBean<Any>) {
                    dismissLoading()
                    uc.turnOrderEvent.call()
                    showSuccessToast(t.msg)
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    /**
     * 查询报修类型
     */
    fun queryWorkOrderType() {
        model.queryWorkOrderType(repairType,model.getAreaId())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriber200Helper<BaseBean<List<OrderTypeBean>>>() {
                override fun onResult(t: BaseBean<List<OrderTypeBean>>) {
                    subTypeId= t.data!![0].id
                }

                override fun onFailed(msg: String?) {
                }

            })
    }
    /**
     *
     */
    fun getDeptByCompanyId(showDialog:Boolean){
        model.getDeptList(model.getLoginCompanyId().toString())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriber200Helper<BaseBean<List<ComplaintDeptBean>>>() {
                override fun onResult(t: BaseBean<List<ComplaintDeptBean>>) {
                    dismissLoading()
                    if (showDialog){
                        uc.queryDeptCompleteEvent.postValue(t.data)
                    }else{
                        if (null!=t.data&& t.data!!.isNotEmpty()){
                            deptName.set(t.data!![0].deptName)
                            deptId= t.data!![0].deptId.toString()
                        }
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    /**
     * 根据部门获取人员列表
     */
    fun getUsersByDeptId() {
        if (ObjectUtils.isEmpty(deptId)) {
            showNormalToast("请选择部门")
            return
        }
        model.getUsersByDeptId(model.getAreaId(), model.getLoginCompanyId().toString(), deptId)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<List<UserBean>>>() {
                override fun onResult(t: BaseBean<List<UserBean>>) {
                    dismissLoading()
                    if (t.code == 200) {
                        uc.queryUserCompleteEvent.postValue(t.data)
                    } else {
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
}